package main

import (
	"bufio"
	"encoding/binary"
	"fmt"
	"net"
	"os"
	"strings"
)

func write(conn net.Conn, data []byte) (int, error) {

	// 写数据长度
	var pkgLen = uint32(len(data))
	var bytes [4]byte
	binary.BigEndian.PutUint32(bytes[0:4], pkgLen)
	n, err := conn.Write(bytes[:4])

	if err != nil {
		fmt.Printf("Write data length error=%v\n", err)
		return n, err
	}

	// 写数据
	n, err = conn.Write(data)

	if err != nil {
		fmt.Printf("Write data error=%v\n", err)
		return n, err
	}

	return n, err
}

func main() {

	address := "127.0.0.1:9999"

	// 建立连接
	conn, err := net.Dial("tcp", address)

	// 关闭连接
	defer conn.Close()

	if err != nil {
		fmt.Printf("Net connect error=%v\n", err)
		return
	}

	// 使用控制台标准输入创建reader对象
	reader := bufio.NewReader(os.Stdin)

	for {

		// 读取控制台输入
		line, err := reader.ReadString('\n')

		if err != nil {
			fmt.Printf("Read stdin line error=%v\n", err)
		} else {

			// 退出
			if strings.TrimSpace(line) == "quit" {
				break
			}

			// 写数据
			_, err = write(conn, []byte(line))
			//_, err := conn.Write([]byte(line))
			if err != nil {
				fmt.Printf("Write line error=%v\n", err)
			}
		}
	}
}
